<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
      v-loading="formLoading"
    >
      <el-form-item label="方案ID" prop="relaPlmId">
        {{ formData.relaPlmId }}
      </el-form-item>
      <el-form-item label="方案名称" prop="planName">
        {{ formData.planName }}
      </el-form-item>
      <el-form-item label="适用范围" prop="applyFlag">
            <el-select v-model="formData.applyFlag">
              <el-option
                v-for="dict in applyFlags"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="适用楼栋" prop="houseIds" v-if="formData.applyFlag == 1">
        <el-button icon="el-icon-search" @click="selectHouse()">选择楼栋</el-button>
        <el-table :data="houseList" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="楼栋地址" align="left" prop="houseName" />
          <el-table-column label="操作" align="center" width="90px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="deleteHouse(scope.row.houseId)"
                v-hasPermi="['zwsj:meter-price-plan:sync']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <HouseSelect
    ref="houseSelectRef"
    @confirm-house="confirmHouse"
  />
</template>
<script setup lang="ts">
import { MeterPricePlanApi, MeterPricePlanVO } from '@/api/zwsj/meterpriceplan'
import HouseSelect from '@/views/zwsj/common/HouseSelect.vue'

/** 电价方案 表单 */
defineOptions({ name: 'MeterPricePlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const applyFlags = ref([
  {value : 0 , label: '通用'},
  {value : 1 , label: '楼栋'},
])

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  applyFlag: undefined,
  planName: undefined,
  relaPlmId: undefined,
  houseIds: [],
  houseList: [],
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
//已选择的楼栋列表
const houseList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MeterPricePlanApi.getMeterPricePlan(id)
      houseList.value = formData.value.houseList
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    //封装楼栋ID
    if(houseList.value.length >0){
      let houseIds = houseList.value.map(item => item.houseId)
      formData.value.houseIds = houseIds
    }
    console.info(formData.value)
    const data = formData.value as unknown as MeterPricePlanVO
    console.info(data)
    await MeterPricePlanApi.updateMeterPricePlan(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    applyFlag: undefined,
    planName: undefined,
    relaPlmId: undefined,
    houseIds: [],
    houseList: [],
  }
  formRef.value?.resetFields()
}


// 选择分账功能
const houseSelectRef = ref()
const selectHouse = async () => {
  houseSelectRef.value.open()
}
const confirmHouse = async (house: any) => {
    //formData.value.houseName = house.name
    //formData.value.houseId = house.id
   if(houseList.value.includes(house.id)){
    return false;
   }else{
    houseList.value.push({houseId: house.id,houseName: house.name})
   }
   console.info(houseList.value)
}

const deleteHouse = async (houseId: number) => {
  console.info(houseId)
  let newList = houseList.value.filter(item => item.houseId !== houseId);
  houseList.value = newList
}
</script>